package Lock_2;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Resource {
    private final Lock lock = new ReentrantLock();
    public void accessResource() {
        if (lock.tryLock()) {
            try {
                System.out.println(Thread.currentThread().getName() + " 获取到锁，正在访问资源");
                Thread.sleep(50); // 模拟资源访问时间
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
                System.out.println(Thread.currentThread().getName() + " 释放锁");
            }
        } else {
            System.out.println(Thread.currentThread().getName() + " 无法获取锁，执行其他操作");
        }
    }
}

public class tryLock使用_资源竞争处理 {
    public static void main(String[] args) {
        final Resource resource = new Resource();

        // 创建30个访问线程
        for (int i = 0; i < 30; i++) {
            new Thread(new Runnable() {
                public void run() {
                    resource.accessResource();
                }
            }, "访问线程-" + i).start();
        }
    }
}